package com.lzx.iteam;

import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.*;
import android.provider.MediaStore;
import android.util.Log;
import android.view.*;
import android.widget.*;
import com.lzx.iteam.adapter.GroupGridAdapter;
import com.lzx.iteam.bean.CloudGroup;
import com.lzx.iteam.bean.GroupManageCreate;
import com.lzx.iteam.bean.GroupMemberData;
import com.lzx.iteam.widget.gridimg.AllEasyGridView;
import com.lzx.iteam.widget.gridimg.EasyGridView;
import com.lzx.iteam.widget.gridimg.ImageAdapter;
import com.lzx.iteam.net.*;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.*;
import io.rong.imageloader.core.DisplayImageOptions;
import io.rong.imageloader.core.ImageLoader;
import io.rong.imageloader.core.assist.ImageScaleType;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import io.rong.imageloader.core.listener.ImageLoadingListener;
import io.rong.imageloader.core.listener.SimpleImageLoadingListener;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.*;

/**
 * Created by shijunting on 15-1-20.
 * 号码圈管理页面
 */
public class ManageGroupActivity extends Activity implements View.OnClickListener, EasyGridView.IHandleGridView {

    private Context mContext;
    private LinearLayout mMainView;
    private ImageView mIvHelp;
    private ImageView mGroupHead;
    private TextView mGroupName, mGroupCreator, mGroupManager, mManageGroupTitle;
    private ToggleButton mGroupAllowAdd;
    private RelativeLayout mGroupDelete, mGroupDissolve, mGroupAllowAddLayout, mGroupNameLayout, mGroupCreateLayout, mGroupManagerLayout, mRlPhotoLayout, mRlAttendanceSetting,mRlPermission;
    private RelativeLayout mApproveSetting,mWeeklyMould;
    private LinearLayout mNotMangerGone,mLlHelp;
    private ScrollView mManageGroupMain;
    private AllEasyGridView mGroupManagerGrid;
    private GridView mNormalGrid;
    private LinearLayout mGroupBack;
    private Button mBtnUpdate;
    private GroupMemberData createrData;
    //    private GroupGridAdapter adapter;
    private String mGroupId;
    private String mContactId;
    private String mCreateType;//-1:虚拟成员(对于团队模板来说); 0:未注册成员;1:普通成员;2:管理者;3:创建者
    private String mGroupImg;
    private String mWhere;
    private int mContactCount;
    private int mGroupType;//是否允许成员添加新人(16或18 都是允许添加新人;2：非允许)
    private String mOriginalGroupName;

    private LayoutInflater mLayoutInflater;
    private PopupWindow mSetPhotoPop;
    private File mCurrentPhotoFile;
    private boolean mIsAllowAddMember;
    private GroupGridAdapter adapter1;
    private ImageAdapter adapter;
    private Bitmap imageBitmap;
    private CloudDBOperation mCloudDBOperation;
    private PreferenceUtil mPreferenceUtil;
    private String mUid;
    private CloudGroup mCloudGroup;


    private static final int PHOTO_PICKED_WITH_DATA = 3821;
    private static final int CAMERA_WITH_DATA = 3824;

    public static final int REQUEST_NEW_GROUP_NAME = 3825;
    private static final int MSG_UPDATEGROUP = 102;
    private static final int MSG_EXIT_GROUP = 103;
    private static final int MSG_REMOVE_GROUP = 104;
    private static final int MSG_REMOVE_MANAGER = 107;
    private static final int MSG_GET_GROUPINFO = 108;
    private static final int CROP_PHOTO = 109;
    private static final int GET_QN_TOKEN = 1000;
    private ArrayList<GroupManageCreate> managerData;
    private ImageLoadingListener animateFirstListener;
    private DisplayImageOptions options;
    protected ImageLoader imageLoader = ImageLoader.getInstance();
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATEGROUP:
                    if (msg.arg1 == 0) {
                        GroupInfo info = (GroupInfo) msg.obj;
                        updateGroupInfo(info);
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(ManageGroupActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(ManageGroupActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case MSG_REMOVE_MANAGER:
                    if (msg.arg1 == 0) {
                        //getGroupCreater(mGroupId, 2);
                        groupGet(mGroupId);
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(ManageGroupActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(ManageGroupActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                        }
                    }
                    break;

                case MSG_EXIT_GROUP:
                    if (msg.arg1 == 0) {
                        Toast.makeText(ManageGroupActivity.this, "退出团队成功", 1).show();
//                        Intent intent = new Intent();
//                        setResult(Constants.REMOVE_EXIT_GROUP, intent);
//                        finish();
                        Intent intent = new Intent(ManageGroupActivity.this, MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent);
                        finish();
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(ManageGroupActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(ManageGroupActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case MSG_REMOVE_GROUP:
                    if (msg.arg1 == 0) {
                        Toast.makeText(ManageGroupActivity.this, "退出团队成功", 1).show();
//                        Intent intent = new Intent();
//                        setResult(Constants.REMOVE_EXIT_GROUP, intent);
//                        finish();
                        Intent intent = new Intent(ManageGroupActivity.this, MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent);
                        finish();
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(ManageGroupActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(ManageGroupActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case MSG_GET_GROUPINFO:
                    if (msg.arg1 == 0) {
                        List<GroupManageCreate> mResult = (List<GroupManageCreate>) msg.obj;
                        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
                        managerData = new ArrayList<GroupManageCreate>();
                        for (int i = 0; i < mResult.size(); i++) {
                            GroupManageCreate bean = mResult.get(i);
                            if (bean.getUserType().equals("3")) {
                                mGroupCreator.setText(bean.getContactName());
                               /* String imgPath = bean.getContactImage() == null ? "" : mGroupImg;
                                imageLoader.displayImage(imgPath, mGroupHead, options, animateFirstListener);*/
                            } else if (bean.getUserType().equals("2")) {
                                managerData.add(bean);
                                HashMap<String, Object> map = new HashMap<String, Object>();
                                map.put("text", bean.getContactName());
                                map.put("icon", bean.getContactImage());
                                list.add(map);

                                if ("1".equals(mCreateType) && bean.userId.equals(mUid)) {
                                    mCreateType = "2";
                                    setInfoView(mCreateType);
                                }

                            }
                        }

                        StringBuilder sb = new StringBuilder();
                        if (managerData != null && managerData.size() != 0) {
                            for (int i = 0; i < managerData.size(); i++) {
                                sb.append(managerData.get(i).getContactName()).append(",");
                            }
                        }
                        if (sb.length() > 0) {
                            mGroupManager.setText(sb.substring(0, sb.length() - 1));
                        } else {
                            mGroupManager.setText("无");
                        }

                        if ("3".equals(mCreateType)) {//创建者
                            adapter = new ImageAdapter(ManageGroupActivity.this, true);
                            mGroupManagerGrid.initData(false, list, adapter);
                            mGroupManagerGrid.setHandleGridView(ManageGroupActivity.this);
                        } else {
                            if (managerData.size() > 0 && managerData != null) {
                                adapter1 = new GroupGridAdapter(ManageGroupActivity.this);
                                adapter1.bindData(3, managerData);
                                mNormalGrid.setAdapter(adapter1);
                            } else {
                                mGroupManagerLayout.setClickable(false);
                            }

                        }
                        if (mResult.size() > 0) {
                            if (!StringUtil.isEmpty(mResult.get(0).getGroupName())) {
                                mGroupName.setText(mResult.get(0).getGroupName());
                            }
                            if (!StringUtil.isEmpty(mResult.get(0).getGroupImg())) {
                                String imgPath = mResult.get(0).getGroupImg() == null ? "" : mResult.get(0).getGroupImg();
                                imageLoader.displayImage(imgPath, mGroupHead, options, animateFirstListener);
                            }
                            if (!StringUtil.isEmpty(mResult.get(0).getGroupType())) {
                                setGroupType(Integer.parseInt(mResult.get(0).getGroupType()));
                            }
                        }

                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(ManageGroupActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(ManageGroupActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case GET_QN_TOKEN:
                    if (msg.arg1 == 0) {
                        Map<String, Object> map = (HashMap<String, Object>) msg.obj;
                        String token = (String) map.get("token");
                        byte[] file = (byte[]) map.get("file");
                        String fileName = (String) map.get("fileName");
                        setPhoto(token, file, fileName);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.manage_number_group);
        mContext = ManageGroupActivity.this;
        initViews();
        initProperty();
        getIntentData();

    }

    private void initViews() {
        mMainView = (LinearLayout) findViewById(R.id.mainview);
        mIvHelp=(ImageView)findViewById(R.id.iv_manage_group_help);
        mLlHelp = (LinearLayout) findViewById(R.id.manage_group_ll_help);
        mLlHelp.setOnClickListener(this);
        mRlPhotoLayout = (RelativeLayout) findViewById(R.id.rl_group_head);
        mRlPhotoLayout.setOnClickListener(this);
        mGroupHead = (ImageView) this.findViewById(R.id.iv_group_head);
        mGroupName = (TextView) this.findViewById(R.id.tv_group_name);
        mGroupCreator = (TextView) this.findViewById(R.id.tv_group_creator);
        mGroupManager = (TextView) this.findViewById(R.id.tv_group_manager);
        mManageGroupTitle = (TextView) this.findViewById(R.id.managegroup_title);
        mGroupAllowAdd = (ToggleButton) this.findViewById(R.id.tb_group_allow_add);
        mGroupAllowAddLayout = (RelativeLayout) this.findViewById(R.id.rl_group_allow_add);
        mGroupDelete = (RelativeLayout) this.findViewById(R.id.rl_group_delete);
        mGroupCreateLayout = (RelativeLayout) this.findViewById(R.id.rl_group_creator);
        mNotMangerGone = (LinearLayout) this.findViewById(R.id.ll_not_manager_gone);
        mGroupDissolve = (RelativeLayout) this.findViewById(R.id.rl_group_dissolve);
        mGroupNameLayout = (RelativeLayout) this.findViewById(R.id.rl_group_name);
        mGroupManagerLayout = (RelativeLayout) this.findViewById(R.id.rl_group_manager);
        mRlAttendanceSetting = (RelativeLayout) this.findViewById(R.id.rl_group_attendance_setting);
        mRlPermission = (RelativeLayout) this.findViewById(R.id.rl_group_permission);
        mGroupBack = (LinearLayout) this.findViewById(R.id.managegroup_btn_back);
        mBtnUpdate = (Button) findViewById(R.id.managergroup_btn_comfrim);
        mBtnUpdate.setOnClickListener(this);
        mApproveSetting = (RelativeLayout) findViewById(R.id.rl_group_approve_setting);
        mApproveSetting.setOnClickListener(this);
        mWeeklyMould = (RelativeLayout) findViewById(R.id.rl_weekly_mould);
        mWeeklyMould.setOnClickListener(this);
        mManageGroupMain = (ScrollView) this.findViewById(R.id.scroll_manage_group_main);
        mGroupManagerGrid = (AllEasyGridView) this.findViewById(R.id.aegv_group_manager);
        mNormalGrid = (GridView) this.findViewById(R.id.gv_group_manager);
        mGroupAllowAdd.setChecked(true);
        mGroupAllowAdd.setTag("mAllowMemberAdd");
        mGroupAllowAddLayout.setOnClickListener(this);
        mGroupDelete.setOnClickListener(this);
        mGroupDissolve.setOnClickListener(this);
        mGroupBack.setOnClickListener(this);
        mGroupNameLayout.setOnClickListener(this);
        mGroupManagerLayout.setOnClickListener(this);
        mRlAttendanceSetting.setOnClickListener(this);
        mRlPermission.setOnClickListener(this);
//        adapter = new GroupGridAdapter(this);

        /*mNormalGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, ContactDetailActivity.class);
                intent.setAction(ContactDetailActivity.ACTION_CLOUD_CONTACT);
                intent.putExtra(ContactDetailActivity.CLOUD_CONTACT_ID, (((GroupMemberData) adapter1.getItem(position)).getContact_id()));
                intent.putExtra(ContactDetailActivity.CLOUD_GROUP_ID, mGroupId);
                intent.putExtra(ContactDetailActivity.CLOUD_IS_CREATOR, Integer.parseInt(mCreateType));
                startActivity(intent);
                ManageGroupActivity.this.overridePendingTransition(R.anim.zoomin, R.anim.zoomout);

            }
        });*/
    }

    public void initProperty() {
        mLayoutInflater = getLayoutInflater();
        options = new DisplayImageOptions.Builder()
                .showStubImage(R.drawable.default_cloud_image)
                .showImageForEmptyUri(R.drawable.default_cloud_image)
                .showImageOnFail(R.drawable.default_cloud_image)
                .cacheInMemory(true)
                .cacheOnDisc(true)
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
        animateFirstListener = new AnimateFirstDisplayListener();
        mCloudDBOperation = new CloudDBOperation(this);
        mPreferenceUtil = PreferenceUtil.getInstance(this);
        mUid = mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1");
    }

    private static class AnimateFirstDisplayListener extends
            SimpleImageLoadingListener {

        static final List<String> displayedImages = Collections
                .synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view,
                                      Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    //FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                }
            }
        }
    }


    private void getIntentData() {
        Intent intent = getIntent();
        mCloudGroup = (CloudGroup) intent.getSerializableExtra("groupData");
        mOriginalGroupName = mCloudGroup.groupName;
        mGroupId = mCloudGroup.groupId + "";
        mGroupType = mCloudGroup.groupType;
        mCreateType = mCloudGroup.userType;
        mGroupImg = mCloudGroup.groupImg;
        mContactCount = mCloudGroup.contactCount;
        mContactId = mCloudGroup.contactId;


        /*mOriginalGroupName = intent.getStringExtra("group_name");
        mGroupId = intent.getStringExtra("group_id");
        mGroupType = intent.getIntExtra("group_type", 0);
        mCreateType = intent.getStringExtra("user_type");
        mGroupImg = intent.getStringExtra("group_img");
        mContactCount = intent.getIntExtra("contact_count", 0);
        mContactId = intent.getStringExtra("contact_id");*/

        mWhere = intent.getStringExtra("where");
        mGroupName.setText(mOriginalGroupName);
        setGroupType(mGroupType);
        mIsAllowAddMember = (mGroupType >> 4) % 2 == 1;
        // 组头像
        if (mGroupImg != null && !StringUtil.isEmpty(mGroupImg)) {
            String imgPath = mGroupImg == null ? "" : mGroupImg;
            imageLoader.displayImage(imgPath, mGroupHead, options, animateFirstListener);
        }

        setInfoView(mCreateType);

        if ("add_manager".equals(mWhere)) {
            mManageGroupMain.setVisibility(View.GONE);
            mIvHelp.setVisibility(View.GONE);
            mGroupManagerGrid.setVisibility(View.VISIBLE);
            mNormalGrid.setVisibility(View.GONE);
        } else if ("structurebackgrid".equals(mWhere)) {
            mManageGroupMain.setVisibility(View.GONE);
            mIvHelp.setVisibility(View.GONE);
            if ("3".equals(mCreateType)) {
                mGroupManagerGrid.setVisibility(View.VISIBLE);
                mNormalGrid.setVisibility(View.GONE);
            } else {
                mNormalGrid.setVisibility(View.VISIBLE);
                mGroupManagerGrid.setVisibility(View.GONE);
            }
            mManageGroupTitle.setText("管理员");
        } else {
            mManageGroupMain.setVisibility(View.VISIBLE);
            mIvHelp.setVisibility(View.VISIBLE);
            mGroupManagerGrid.setVisibility(View.GONE);
            mNormalGrid.setVisibility(View.GONE);
        }
        if (intent.getStringExtra("err_name") != null && !"".equals(intent.getStringExtra("err_name"))) {
            Toast.makeText(ManageGroupActivity.this, "对不起,不能设置" + intent.getStringExtra("err_name") + "为管理员", Toast.LENGTH_LONG).show();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        groupGet(mGroupId);
    }


    private void setInfoView(String type) {
        if ("2".equals(type) || "3".equals(type)) {
            mManageGroupTitle.setText(getResources().getString(R.string.manage_number_group));
        } else {
            mManageGroupTitle.setText(getResources().getString(R.string.number_group_detail));
        }

        if ("-1".equals(type) || "1".equals(type)) {//普通用户
            mNotMangerGone.setVisibility(View.GONE);
            ((TextView) findViewById(R.id.disband_group)).setText("退出团队");
            mGroupNameLayout.setClickable(false);
            mRlPhotoLayout.setClickable(false);
            mGroupManagerLayout.setClickable(false);
        } else {
            mNotMangerGone.setVisibility(View.VISIBLE);
            if ("2".equals(type)) {//管理员
                ((TextView) findViewById(R.id.disband_group)).setText("退出团队");
            }
            mGroupNameLayout.setClickable(true);
            mRlPhotoLayout.setClickable(true);
            mGroupManagerLayout.setClickable(true);
        }
    }

    private void setGroupType(int type) {
        if (type == 1) {
            mGroupAllowAdd.setChecked(true);
        } else {
            mGroupAllowAdd.setChecked(false);
        }
    }


    private int getGroupType() {
        int allowAdd = 0;
        if (mGroupAllowAdd.isChecked()) {
            allowAdd = 1;
        }
        return allowAdd;

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_group_allow_add:
                mGroupAllowAdd.toggle();
                groupUpdate(mGroupId + "", null, String.valueOf(getGroupType()), null);
                break;
            case R.id.manage_group_ll_help:
                Intent help = new Intent(ManageGroupActivity.this, WebViewActivity.class);
                help.putExtra("title", "团队有哪些管理功能?");
                help.putExtra("type", 13);
                startActivity(help);
                break;
            case R.id.rl_group_delete:
                Intent intent1 = new Intent(ManageGroupActivity.this, CloudDialerActivity.class);
                intent1.setAction("manage_delete_member");
                intent1.putExtra("contact_id", mContactId);
                intent1.putExtra("groupData", mCloudGroup);
                startActivity(intent1);
                break;
            case R.id.rl_group_dissolve:
                showExitGroupDlg();
                break;
            case R.id.managegroup_btn_back:
                if (mGroupManagerGrid.getVisibility() == View.VISIBLE || mNormalGrid.getVisibility() == View.VISIBLE) {
                    mManageGroupMain.setVisibility(View.VISIBLE);
                    mIvHelp.setVisibility(View.VISIBLE);
                    mGroupManagerGrid.setVisibility(View.GONE);
                    mNormalGrid.setVisibility(View.GONE);
                    mManageGroupTitle.setText(getResources().getString(R.string.manage_number_group));
                } else if ("structureback".equals(mWhere) || "structurebackgrid".equals(mWhere)) {
                    Intent intent2 = new Intent();
                    intent2.putExtra("group_id", mGroupId);
                    setResult(Constants.MANAGER_GROUP_NORMAL, intent2);
                    finish();
//                } else if () {
//                    Intent intent=new Intent(ManageGroupActivity.this,CloudGroupStructureActivity.class);
//                    intent.putExtra("group_id", mGroupId);
//                    intent.putExtra("group_name",mOriginalGroupName);
//                    intent.putExtra("pid", "");
//                    intent.putExtra("group_img", mGroupImg);
//                    intent.putExtra("group_type", mGroupType);
//                    intent.putExtra("user_type", mCreateType);
//                    intent.putExtra("contact_count",mContactCount);
//                    startActivity(intent);
                } else {
                    CloudDialerActivity.mBatchOperationType = 0;
//                    Intent intent=new Intent(ManageGroupActivity.this,CloudDialerActivity.class);
//                    startActivity(intent);
                    finish();
                }
                break;
            case R.id.rl_group_name:
                Intent intent = new Intent(ManageGroupActivity.this, UpdateGroupNameActivity.class);
                intent.putExtra("old_name", mGroupName.getText().toString());
                startActivityForResult(intent, REQUEST_NEW_GROUP_NAME);
                break;
            case R.id.rl_group_manager:
                mManageGroupMain.setVisibility(View.GONE);
                mIvHelp.setVisibility(View.GONE);
                if ("3".equals(mCreateType)) {
                    mGroupManagerGrid.setVisibility(View.VISIBLE);
                    mNormalGrid.setVisibility(View.GONE);
                } else {
                    mNormalGrid.setVisibility(View.VISIBLE);
                    mGroupManagerGrid.setVisibility(View.GONE);
                }
                mManageGroupTitle.setText("管理员");
                break;
            case R.id.rl_group_creator:
                Intent detailIntent = new Intent(mContext, CloudContactDetailActivity.class);
                detailIntent.setAction(CloudContactDetailActivity.ACTION_CLOUD_CONTACT);
                detailIntent.putExtra("", createrData.getUser_id());
                detailIntent.putExtra("group_id", mGroupId);
                detailIntent.putExtra("contact_id", createrData.getContact_id());
                detailIntent.putExtra("current_contact_id", mContactId);
                detailIntent.putExtra("group_id", mGroupId);
                detailIntent.putExtra("group_name", mOriginalGroupName);
                detailIntent.putExtra("user_id", createrData.getUser_id());
                detailIntent.putExtra("user_type", mCreateType);
                startActivity(detailIntent);
                break;
            case R.id.rl_group_head:
                showSetPhotoPop();
                break;
            case R.id.managergroup_btn_comfrim:
                //判断数据是否发生了变化
                String groupName = mGroupName.getText().toString();
                boolean allowAdd = mGroupAllowAdd.isChecked();
                if (!(groupName.equals(mOriginalGroupName) && allowAdd == mIsAllowAddMember && !mIsUpdateImag)) {

                }
                // 向服务器提交
                break;
            case R.id.rl_group_attendance_setting:
                Intent attendance = new Intent(ManageGroupActivity.this, AttendanceCreateActivity.class);
                attendance.putExtra("group_id", mGroupId);
                attendance.putExtra("group_name", mOriginalGroupName);
                attendance.putExtra("user_type", mCreateType);
                attendance.putExtra("contact_id", mContactId);
                startActivity(attendance);
                break;
            case R.id.rl_group_approve_setting:
                Intent approve = new Intent(ManageGroupActivity.this, ScheduleManagerActivity.class);
                approve.putExtra("groupData",mCloudGroup);
                approve.setAction("approval_leader_add");
                startActivity(approve);
                break;
            case R.id.rl_weekly_mould:
                Intent mould = new Intent(ManageGroupActivity.this,WeeklyTemplateActivity.class);
                mould.putExtra("group_id",mGroupId);
                startActivity(mould);
                break;
            case R.id.rl_group_permission:
                Intent permission = new Intent(ManageGroupActivity.this, TeamPermissionActivity.class);
                permission.putExtra("group_id", mGroupId);
                startActivity(permission);
                break;
        }
    }

    private void groupUpdate(String groupId, String groupName, String groupType, String groupImg) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, groupId));
        if (groupName != null) {
            params.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_NAME, groupName));
        }
        if (groupType != null) {
            params.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_TYPE, groupType));
        }
        if (groupImg != null) {
            params.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_IMG, groupImg));
        }
        UpdateGroupMessage updateGroupMessage = new UpdateGroupMessage(mHandler.obtainMessage(MSG_UPDATEGROUP));
        updateGroupMessage.mApi = AsynHttpClient.API_GROUP_UPDATE;
        updateGroupMessage.mParams = params;
        AsynHttpClient.getInstance(mContext).execCcHttp(updateGroupMessage);
    }

    @Override
    public void addImage() {//点击添加按钮
        Intent intent = new Intent(ManageGroupActivity.this, CloudDialerActivity.class);
        intent.putExtra("group_id", mGroupId);
        intent.putExtra("group_name", mOriginalGroupName);
        intent.putExtra(Constants.INTENT_TAG_NAME, mOriginalGroupName);
        intent.putExtra("contact_count", mContactCount);
        intent.putExtra("contact_id", mContactId);
        intent.putExtra("create_type", mCreateType);
        intent.setAction("manage_add_manager");
        startActivity(intent);
    }

    @Override
    public void delImage(int position) {//点击删除按钮
//        mGroupManagerGrid.getData().remove(position);

        //removeManager(mGroupId, (String) mGroupManagerGrid.getData().get(position).get("user_id"));
        removeManager(managerData.get(position).contactId);

    }

    @Override
    public void queryImage(int position) {
        /*Intent intent = new Intent(mContext, ContactDetailActivity.class);
        intent.setAction(ContactDetailActivity.ACTION_CLOUD_CONTACT);
        intent.putExtra(ContactDetailActivity.CLOUD_CONTACT_ID, managerData.get(position).contactId);
        intent.putExtra(ContactDetailActivity.CLOUD_GROUP_ID, mGroupId);
        intent.putExtra(ContactDetailActivity.CLOUD_IS_CREATOR, Integer.parseInt(mCreateType));
        startActivity(intent);
        ManageGroupActivity.this.overridePendingTransition(R.anim.zoomin, R.anim.zoomout);*/
    }


    /**
     * 更新团队信息
     */
    static class UpdateGroupMessage extends CcMsgStructure {
        private Message mmCallback;

        public UpdateGroupMessage(Message callback) {
            mmCallback = callback;
        }

        @Override
        public void onReceive(JSONObject data) {
            try {
                JSONObject groupData = data.getJSONObject("data");
                String groupName = groupData.getString("group_name");
                String groypType = groupData.getString("group_type");
                String groupImg = groupData.getString("group_img");
                GroupInfo info = new GroupInfo(groupName, groypType, groupImg);
                if (mmCallback != null) {
                    mmCallback.obj = info;
                    mmCallback.sendToTarget();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(int error, Object ret) {
            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }
            }
            if (mmCallback != null) {
                mmCallback.arg1 = error;
                if (!StringUtil.isEmpty(errorMsg)) {
                    mmCallback.obj = errorMsg;
                } else {
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }


    public void updateGroupInfo(GroupInfo info) {
        if (info != null) {
            if (!StringUtil.isEmpty(info.groupName)) {
                mGroupName.setText(info.groupName);
                mCloudDBOperation.updateCloudGrupName(mGroupId, info.groupName);
            }
            if (!StringUtil.isEmpty(info.groupImg)) {
                String imgPath = info.groupImg == null ? "" : info.groupImg;
                imageLoader.displayImage(imgPath, mGroupHead, options, animateFirstListener);
            }
            if (!StringUtil.isEmpty(info.groupType)) {
                setGroupType(Integer.parseInt(info.groupType));
            }
        }
    }


    /**
     * 弹出拍照和从相册选择popwindow
     */
    private void showSetPhotoPop() {
        View mainView = mLayoutInflater.inflate(R.layout.alert_setphoto_menu_layout, null);
        Button btnTakePhoto = (Button) mainView.findViewById(R.id.btn_take_photo);
        btnTakePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSetPhotoPop.dismiss();
                doTakePhoto();
            }
        });
        Button btnCheckFromGallery = (Button) mainView.findViewById(R.id.btn_check_from_gallery);
        btnCheckFromGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSetPhotoPop.dismiss();
                doPickPhotoFromGallery();
            }
        });
        Button btnCancle = (Button) mainView.findViewById(R.id.btn_cancel);
        btnCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSetPhotoPop.dismiss();
            }
        });
        mSetPhotoPop = new PopupWindow(this);
        mSetPhotoPop.setBackgroundDrawable(new BitmapDrawable());
        mSetPhotoPop.setFocusable(true);
        mSetPhotoPop.setTouchable(true);
        mSetPhotoPop.setOutsideTouchable(true);
        mSetPhotoPop.setContentView(mainView);
        mSetPhotoPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mSetPhotoPop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        mSetPhotoPop.setAnimationStyle(R.style.bottomStyle);
        mSetPhotoPop.showAtLocation(mMainView, Gravity.BOTTOM, 0, 0);
        mSetPhotoPop.update();

        mainView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mSetPhotoPop.dismiss();
                return false;
            }
        });
    }

    /**
     * 调用系统相机拍照
     */
    protected void doTakePhoto() {
        try {
            // Launch camera to take photo for selected contact
            File file = new File(Environment.getExternalStorageDirectory() + "/Yun/Images");
            if (!file.exists()) {
                file.mkdirs();
            }
            mCurrentPhotoFile = new File(file, "image");
            final Intent intent = getTakePickIntent(mCurrentPhotoFile);
            startActivityForResult(intent, CAMERA_WITH_DATA);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, R.string.photoPickerNotFoundText, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * Constructs an intent for capturing a photo and storing it in a temporary
     * file.
     */
    public static Intent getTakePickIntent(File f) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        return intent;
    }

    /**
     * 剪切图片
     */
    protected void doCropPhoto(File f) {
        try {
            // Add the image to the media store
            MediaScannerConnection.scanFile(this, new String[]{
                    f.getAbsolutePath()
            }, new String[]{
                    null
            }, null);

            // Launch gallery to crop the photo
            final Intent intent = getCropImageIntent(Uri.fromFile(f));
            startActivityForResult(intent, CROP_PHOTO);
        } catch (Exception e) {
            Toast.makeText(this, R.string.photoPickerNotFoundText, Toast.LENGTH_LONG).show();
        }
    }

    private static final int ICON_SIZE = 96;

    /**
     * 获取系统剪裁图片的Intent.
     */
    public static Intent getCropImageIntent(Uri photoUri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(photoUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", ICON_SIZE);
        intent.putExtra("outputY", ICON_SIZE);
        intent.putExtra("return-data", true);
        return intent;
    }

    /**
     * 从相册选择图片
     */
    protected void doPickPhotoFromGallery() {
        try {
            // Launch picker to choose photo for selected contact
            final Intent intent = getPhotoPickIntent();
            startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, R.string.photoPickerNotFoundText, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 获取调用相册的Intent
     */
    public static Intent getPhotoPickIntent() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        return intent;
    }

    /**
     * 093.
     * 收缩图片
     *
     * @param uri
     */
    private final int PHOTO_RESOULT = 1111;

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");//调用Android系统自带的一个图片剪裁页面,
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");//进行修剪
// aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", ICON_SIZE);
        intent.putExtra("outputY", ICON_SIZE);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_RESOULT);
    }

    private boolean mIsUpdateImag;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            switch (requestCode) {
                case PHOTO_PICKED_WITH_DATA:
                    mIsUpdateImag = true;
                    startPhotoZoom(data.getData());
                    break;
                case CROP_PHOTO:
                    mIsUpdateImag = true;
                    imageBitmap = data.getParcelableExtra("data");
                    getQnToken(PhotoUtil.compressAvatarImage(imageBitmap));
                    break;
                case CAMERA_WITH_DATA:
                    Bitmap bitmap = PhotoUtil.readBitmapFromPath(this, mCurrentPhotoFile.getAbsolutePath(), false);
                    int degree = PhotoUtil.getExifOrientation(mCurrentPhotoFile.getAbsolutePath());
                    if (degree != 0) {
                        bitmap = PhotoUtil.rotaingImageView(bitmap, degree);
                        mCurrentPhotoFile = PhotoUtil.saveBitmaptoSdCard(bitmap, this, "/Yun/Images");
                    }
                    doCropPhoto(mCurrentPhotoFile);
                    break;
                case PHOTO_RESOULT:
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        imageBitmap = extras.getParcelable("data");
                        getQnToken(PhotoUtil.compressAvatarImage(imageBitmap));
                    }
                    break;

                case REQUEST_NEW_GROUP_NAME:
                    String newName = data.getExtras().getString("new_name");
                    if (!StringUtil.isEmpty(newName)) {
                        groupUpdate(mGroupId + "", newName, null, null);
                    }
                    break;
            }
        }
    }

    static class GroupInfo {
        String groupName;
        String groupType;
        String groupImg;

        public GroupInfo(String name, String type, String img) {
            this.groupName = name;
            this.groupType = type;
            this.groupImg = img;
        }
    }

    /**
     * 退出/解散某团队
     *
     * @param groupId
     */
    private void exitGroup(String groupId) {
        GetMsgHttpReceiver getMsg = null;
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, groupId));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTACT_ID, mContactId));
        getMsg = new GetMsgHttpReceiver(mHandler.obtainMessage(MSG_REMOVE_GROUP));
        getMsg.mApi = AsynHttpClient.API_GROUP_REMOVE;
        getMsg.mParams = params;
        AsynHttpClient.getInstance(mContext).execCcHttp(getMsg);
    }

    private void removeManager(String contactId) {
        GetMsgHttpReceiver getMsg = new GetMsgHttpReceiver(mHandler.obtainMessage(MSG_REMOVE_MANAGER));
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        //params.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, groupId));
        //params.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_ID, userId));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTACT_ID, mContactId));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_MANAGER_CONTACT_ID, contactId));
        getMsg.mApi = AsynHttpClient.API_GROUP_REMOVE_MANAGER;
        getMsg.mParams = params;
        AsynHttpClient.getInstance(this).execCcHttp(getMsg);
    }

    /**
     * 退出或解散群组
     */
    public void showExitGroupDlg() {
        AllDialogUtil dialogUtil = AllDialogUtil.getInstance(ManageGroupActivity.this);
        String okText = mContext.getString(R.string.label_btn_ok);
        String cancelText = mContext.getString(R.string.cancel);
        if (mCreateType.equals("3")) {
            dialogUtil.titleDeleteMsgStyle("解散" + mOriginalGroupName + "团队", okText, cancelText, "团队簿解散后,所有成员将失去此团队\n此动作不可恢复,是否确认解散?");
        } else {
            dialogUtil.titleDeleteMsgStyle("退出" + mOriginalGroupName + "团队", okText, cancelText, "团队团队后,所有成员将失去您的联系方式\n是否确认退出?");
        }
        dialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog) {
                exitGroup(mGroupId);
                lDialog.dismiss();
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();

            }

        });
    }

    private void groupGet(String groupId) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        params.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, groupId));
        GetGroupInfoMsg getInfo = new GetGroupInfoMsg(mHandler.obtainMessage(MSG_GET_GROUPINFO));
        getInfo.mApi = AsynHttpClient.API_GROUP_GET;
        getInfo.mParams = params;
        AsynHttpClient.getInstance(mContext).execCcHttp(getInfo);
    }


    public void getQnToken(byte[] file) {
        String fileName = UUID.randomUUID().toString() + System.currentTimeMillis();
        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_KEY, fileName));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_GID, mGroupId));
        GetQnTokenMsg getQnTokenMsg = new GetQnTokenMsg(mHandler.obtainMessage(GET_QN_TOKEN), file, fileName);
        getQnTokenMsg.mApi = AsynHttpClient.API_QN_GET_GROUP_TOKEN;
        getQnTokenMsg.mParams = mList;
        AsynHttpClient.getInstance(this).execUserHttp(getQnTokenMsg);
    }

    public void setPhoto(String token, byte[] file, String fileName) {
        Log.d("七牛--token", token);
        Log.d("七牛--fileName", fileName);
        DialerApp.getUploadManager(this).put(file, fileName, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject response) {
                        Log.d("七牛--info.isOk()", info.isOK() + "--response" + response);
                        mGroupHead.setImageBitmap(imageBitmap);
                    }
                }, null);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (mGroupManagerGrid.getVisibility() == View.VISIBLE || mNormalGrid.getVisibility() == View.VISIBLE) {
                    mManageGroupMain.setVisibility(View.VISIBLE);
                    mIvHelp.setVisibility(View.VISIBLE);
                    mGroupManagerGrid.setVisibility(View.GONE);
                    mNormalGrid.setVisibility(View.GONE);
                    mManageGroupTitle.setText(getResources().getString(R.string.manage_number_group));
                } else if ("structureback".equals(mWhere) || "structurebackgrid".equals(mWhere)) {
                    Intent intent2 = new Intent();
                    intent2.putExtra("group_id", mGroupId);
                    setResult(Constants.MANAGER_GROUP_NORMAL, intent2);
                    finish();
                } else {
                    CloudDialerActivity.mBatchOperationType = 0;
//                    Intent intent=new Intent(ManageGroupActivity.this,CloudDialerActivity.class);
//                    startActivity(intent);
                    finish();
                }
                break;
        }
//        return super.onKeyDown(keyCode, event);
        return true;
    }
}
